package leetcode;

public class LeetCode29 {

    public static void main(String[] args) {
        System.out.println(Integer.MAX_VALUE);
        System.out.println(Integer.MIN_VALUE);
        System.out.println(Math.abs(-2147483648));
        System.out.println(Math.abs(-2147483647));
    }

    //二分法会使用乘法和除法
    //加减 为运算
    public int divide1(int dividend, int divisor) {
        int result = 0, absDividend = dividend >= Integer.MIN_VALUE ? Math.abs(dividend) : Integer.MAX_VALUE, absDivisor = Math.abs(divisor);
        while (true) {
            absDividend -= absDivisor;
            if (absDividend >= 0) result++;
            else break;
        }

        if ((dividend > 0 && divisor > 0) || dividend < 0 && divisor < 0)
            return result;
        else
            return result * -1;
    }

    public int divide2(int dividend, int divisor) {
        int result = 0, absDividend = Math.abs(dividend), absDivisor = Math.abs(divisor);
        while (absDividend >= 0) {
            absDividend -= absDivisor;
            result++;
        }
        if ((dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0))
            return result - 1;
        else
            return (result - 1) * -1;
    }

    public int divide3(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1)
            return Integer.MAX_VALUE;

        boolean k = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0);
        int result = 0;
        dividend = -Math.abs(dividend);
        divisor = -Math.abs(divisor);
        while (dividend <= divisor) {
            dividend -= divisor;
            result += 1;
        }
        return k ? result : -result;
    }

    public int divide(int dividend, int divisor) {
        if (dividend == Integer.MIN_VALUE && divisor == -1)
            return Integer.MAX_VALUE;

        boolean k = (dividend > 0 && divisor > 0) || (dividend < 0 && divisor < 0);
        int result = 0;
        dividend = -Math.abs(dividend);
        divisor = -Math.abs(divisor);
        while (dividend <= divisor) {
            int temp = divisor;
            int c = 1;
            while (dividend - temp <= temp) {
                temp = temp << 1;
                c = c << 1;
            }
            dividend -= temp;
            result += c;
        }
        return k ? result : -result;
    }
//------------------------------------------------------------------
}
